<?php

/* 运费区域 shippingarea */
class ShippingareaModel extends BaseModel
{
	var $table  = 'shipping_area';
	var $prikey = 'shipping_area_id';
	var $alias  = 'gs';
	var $_name  = 'goodsspec';

	var $_relation  = array(
	// 一个运费区域只能属于一个运费模板
	'belongs_to_shipping' => array(
	'model'         => 'shipping',
	'type'          => BELONGS_TO,
	'foreign_key'   => 'shipping_id',
	'reverse'       => 'has_shippingarea',
	),

	);


	function get_shipping_area_list($shipping_id)
	{
		$area_sql = "SELECT * from " . $this->table ." where shipping_id = $shipping_id order by shipping_area_id asc limit 100";
		$row = $this->db->getAll($area_sql);
		if(is_array($row))
		{
			foreach($row as $key=>$val)
			{
				$region_id =  explode(',',$val['region_id']);
				$region_name = '';
				foreach ($region_id as $k => $value)
				{
					$value  =  intval($value);
					$region_name .= 'r-'.$value.',';
				}

				$row[$key]['region_id']= trim($region_name,',');
			}
			return $row;
		}

	}

	function add($shipping_id,$data)
	{
		//默认运费地址
		$area_data['shipping_id'] = $shipping_id;
		//$area_data['shipping_way'] =  1;//快递,2为货运，拓展用
		$area_data['shipping_area_name'] =  '全国(除指定地区以外)';
		$area_data['region_id'] =  1;
		$area_data['item'] =  $data['item'];
		$area_data['item_price'] =  $data['item_price'];
		$area_data['step'] =  $data['step'];
		$area_data['step_price'] =  $data['step_price'];

		$shipping_area_id = parent::add($area_data);

		//指定区域
		if(is_array($data['shipping_area']))
		{
			foreach($data['shipping_area'] as $key=>$val)
			{
				$area['shipping_id'] = $shipping_id;

				$area['region_id'] =  str_replace('r-','',$val[1]);
				$region_id =  explode(',',$area['region_id']);
				$region_name = '';
				foreach ($region_id as $k => $value)
				{
					$value  =  intval($value);
					$region_name .= $this->db->getOne("SELECT region_name from " . DB_PREFIX ."region  where region_id = $value").',';
				}
				$area['shipping_area_name'] = trim($region_name,',');
				$area['item'] =  floatval($val[2]);
				$area['item_price'] =  floatval($val[3]);
				$area['step'] =  floatval($val[4]);
				$area['step_price'] =  floatval($val[5]);

				parent::add($area);

			}
		}
	}
}
?>